package com.atguigu.service.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.service.vod.service.MediaService;
import com.atguigu.service.vod.util.VodProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class MediaServiceImpl implements MediaService {
    @Autowired
    VodProperties vodProperties;

    //上传视频
    @Override
    public String upload(MultipartFile file) {
        try {
            UploadStreamRequest request = new UploadStreamRequest(vodProperties.getAccessKeyId(),
                    vodProperties.getAccessKeySecret(),
                    file.getOriginalFilename(),
                    file.getOriginalFilename(),
                    file.getInputStream());
            /* 工作流ID(可选) */
            request.setWorkflowId(vodProperties.getWorkflowId());
            // new HttpClient  创建客户端对象
            UploadVideoImpl uploader = new UploadVideoImpl();
            // client.excute(httpPost)
            UploadStreamResponse response = uploader.uploadStream(request);
            if (response.isSuccess()) {
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                //返回上传成功后视频的id
                return response.getVideoId();
            } else {
                /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
               log.error("VideoId=" + response.getVideoId() + "\n");
               log.error("ErrorCode=" + response.getCode() + "\n");
               log.error("ErrorMessage=" + response.getMessage() + "\n");
                throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR ,
                        new RuntimeException(response.getMessage()));
            }
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR  ,e);
        }
    }

    //获取视频地址
    @Override
    public String getPlayUrl(String videoId) {
        DefaultProfile profile = DefaultProfile.getProfile(vodProperties.getRegionId(),
                vodProperties.getAccessKeyId() ,
                vodProperties.getAccessKeySecret());
        DefaultAcsClient client = new DefaultAcsClient(profile);
        GetPlayInfoResponse response = new GetPlayInfoResponse();
        try {
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            request.setVideoId(videoId);
            response = client.getAcsResponse(request);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
            //播放地址
            return playInfoList.get(0).getPlayURL();
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            throw new GuliException(ResultCodeEnum.FETCH_PLAYAUTH_ERROR , e);
        }
    }

    //获取加密视频验证
    @Override
    public String getPlayAuth(String videoId) {
        DefaultProfile profile = DefaultProfile.getProfile(vodProperties.getRegionId(),
                vodProperties.getAccessKeyId() ,
                vodProperties.getAccessKeySecret());
        DefaultAcsClient client = new DefaultAcsClient(profile);
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        try {
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(videoId);
            //eyJTZWN1cml0eVRva2VuIjoiQ0FJU2h3TjFxNkZ0NUIyeWZTaklyNWJTUE43VnFZMFFnb2pUT24vbXRGUWhidTRZM1l2WXNUejJJSHBLZVhkdUFlQVhzL28wbW1oWjcvWVlsck1xRmNBVkh4T2ZNWkFvdnNRTnFGNzRKcExGc3QySjZyOEpqc1ZEa2VBeTBsbXBzdlhKYXNEVkVmbDJFNVhFTWlJUi8wMGU2TC8rY2lyWXBUWEhWYlNDbFo5Z2FQa09Rd0M4ZGtBb0xkeEtKd3hrMn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LFwiUGxheURvbWFpblwiOlwic2gyMTAzMjUteGcuZ3VsaW9ubGluZS5zaG9wXCIsXCJTaWduYXR1cmVcIjpcIk10Ni9mT1dtbHBUUlpWczNQb1NMUWQrWUt5VT1cIn0iLCJWaWRlb01ldGEiOnsiU3RhdHVzIjoiTm9ybWFsIiwiVmlkZW9JZCI6ImE1MGNjMTMxNTA2ODRhMjdiYjhhMDhhMWVjYTVlMDBmIiwiVGl0bGUiOiJjYy5tcDQiLCJDb3ZlclVSTCI6Imh0dHA6Ly9zaDIxMDMyNS14Zy5ndWxpb25saW5lLnNob3AvYTUwY2MxMzE1MDY4NGEyN2JiOGEwOGExZWNhNWUwMGYvc25hcHNob3RzL2E2MzBjMjhmNGVlYjRjNmI4NjZhN2JlM2E5ZjQzYjdlLTAwMDAyLmpwZyIsIkR1cmF0aW9uIjoxNi4yNzY3fSwiQWNjZXNzS2V5SWQiOiJTVFMuTlVnd2RhRFIxNUo4OFlXUFR0YmE0Mk5zUyIsIlBsYXlEb21haW4iOiJzaDIxMDMyNS14Zy5ndWxpb25saW5lLnNob3AiLCJBY2Nlc3NLZXlTZWNyZXQiOiJCVEhEM25IaUVyU0pCc25WRVkxMTJSWHR6Yno1ZFo3VkpZOEN6dEJid2hjdyIsIlJlZ2lvbiI6ImNuLXNoYW5naGFpIiwiQ3VzdG9tZXJJZCI6MTY3ODI3MzQzMDg4MjE1MX0=
            request.setAuthInfoTimeout(vodProperties.getTimeout());//设置播放凭证过期时间为3000秒
            response = client.getAcsResponse(request);
            //播放凭证
            System.out.print("PlayAuth = " + response.getPlayAuth() + "\n");
            return response.getPlayAuth();
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.FETCH_PLAYAUTH_ERROR , e);
        }
    }
}
